import { getUserInfo, logout } from "@/api";
import { defineStore } from "pinia";
import { useSocketInfoStore } from "./webSocket";
import { REMOVE_CACHE } from "@/utils/localCache";
import { useRouter } from "vue-router";

export const useUserInfoStore = defineStore("userInfo", {
  state: (): {
    user: USER.info;
    isLogin: boolean;
  } => ({
    // 用户信息
    user: {
      id: 0,
      username: "",
      avatar: "",
      sex: 1,
      activeStatus: 1,
    },
    // 当前登录状态
    isLogin: false,
  }),
  getters: {
    // 获取头像
    getHeader(){
      return (img?: string) => `/header/avatar${img ?? this.user.avatar}.png`
    }
  },
  actions: {
    // 获取并设置用户信息
    async getUserInfo() {
      // 发送获取用户信息的请求
      const res = await getUserInfo(this.user.username);
      for (const i in this.user) {
        this.user[i] = res[i];
      }
    },
    // 注销登录
    toLogout() {
      logout().then((res) => {
        if (!res) return;
        const webSocket = useSocketInfoStore();
        // 关闭websocket连接
        webSocket.socket?.close();
        // 清空用户信息
        this.user = {
          id: 0,
          username: "",
          avatar: "",
          sex: 1,
          activeStatus: 1,
        };
        this.isLogin = false;
        // 清空本地token
        REMOVE_CACHE("token");
        // 跳转到登录页
        const router = useRouter()
        router.push("/");
      });
    },
  },
  persist: true,
});
